-- 导入socket 库
local socket = require("socket")
print("lua socket version :",socket._VERSION)
-- tcp 方式访问 http 服务器
do
    local host = "www.baidu.com";
    local file = "/";
    local webFile = nil;
    -- 创建一个 TCP 连接，连接到 HTTP 连接的标准端口 -- 80 端口上
    local sock = assert(socket.connect(host, 80));
    sock:send("GET " .. file .. " HTTP/1.0\r\n\r\n");
    webFile = assert(io.open("webFile.html","w"));
    print("webFile",webFile,"type",type(webFile) )
    while true do
        -- 返回值说明
        -- 一次性接收2^10个数据，如果有2^10个数据则把内容给s
        -- 如果不够，则把数据给partial
        local s, status, partial = sock:receive(2^10)
        webFile:write( s or partial );
        --当主机断开连接时，退出循环 
        if status == "closed" then
            break
        end
    end
    webFile:close();
    sock:close();
    print("Download OK\n")
end 

-- 内置HTTP模块访问http服务器
do 
    local http = require("socket.http")
    local httpFile = nil;
    httpFile = assert(io.open("httpFile.html","w"));
    print("httpFile",httpFile,"type",type(httpFile) )
    local response = http.request("http://www.baidu.com/")
    httpFile:write( response );
end